package com.zbkj.service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.enums.RoleEnum;
import com.zbkj.common.exception.AppException;
import com.zbkj.common.model.admin.SystemAdmin;
import com.zbkj.common.model.admin.SystemRole;
import com.zbkj.common.model.agent.UserAgent;
import com.zbkj.common.model.user.User;
import com.zbkj.common.request.*;
import com.zbkj.common.response.*;
import com.zbkj.common.result.AdminResultCode;
import com.zbkj.common.result.CommonResultCode;
import com.zbkj.common.utils.CrmebUtil;
import com.zbkj.common.utils.SecurityUtil;
import com.zbkj.service.dao.SystemAdminDao;
import com.zbkj.service.service.SystemAdminService;
import com.zbkj.service.service.SystemRoleService;
import com.zbkj.service.service.UserAgentService;
import com.zbkj.service.service.UserService;
import com.zbkj.service.util.BrandUtil;
import jodd.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * SystemAdminServiceImpl 接口实现
 * +----------------------------------------------------------------------
 */
@Service
public class SystemAdminServiceImpl extends ServiceImpl<SystemAdminDao, SystemAdmin> implements SystemAdminService {

    @Resource
    private SystemAdminDao dao;

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAgentService userAgentService;


    /**
     * 通过用户名获取用户
     *
     * @param username 用户名
     * @param type     用户类型
     * @return SystemAdmin
     */
    @Override
    public SystemAdmin selectUserByUserNameAndType(String username, Integer type) {
        List<Integer> types = addSuperRoleType(type);
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getAccount, username);
        lqw.in(SystemAdmin::getType, types);
        lqw.eq(SystemAdmin::getIsDel, false);
        lqw.last(" limit 1");
        return dao.selectOne(lqw);
    }

    /**
     * 后台管理员列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return List
     */
    @Override
    public List<SystemAdminResponse> getList(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带SystemAdminRequest类的多条件查询
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotNull(request.getStatus())) {
            lqw.eq(SystemAdmin::getStatus, request.getStatus());
        }
        if (StrUtil.isNotBlank(request.getRealName())) {
            String decode = URLUtil.decode(request.getRealName());
            lqw.and(i -> i.like(SystemAdmin::getRealName, decode)
                    .or().like(SystemAdmin::getAccount, decode));
        }
        SystemAdmin currentAdmin = SecurityUtil.getLoginUserVo().getUser();
        lqw.eq(SystemAdmin::getMerId, currentAdmin.getMerId());
        // 超级管理员查看平台账户 商户超级管理员查看自己和商户管理员
        // 1=1，2,3 2=2，4
        List<Integer> types = new ArrayList<>();
        if (currentAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            types.add(RoleEnum.MERCHANT_ADMIN.getValue());
            types.add(RoleEnum.SUPER_MERCHANT.getValue());
            lqw.in(SystemAdmin::getType, types);
        } else if (currentAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())) {
            types.add(RoleEnum.PLATFORM_ADMIN.getValue());
            types.add(RoleEnum.SUPER_ADMIN.getValue());
            lqw.in(SystemAdmin::getType, types);
        } else {
            lqw.eq(SystemAdmin::getType, systemRoleService.getRoleTypeByCurrentAdmin());
        }
        if (ObjectUtil.isNotNull(request.getRoles()) && request.getRoles() > 0) {
            lqw.apply(" find_in_set({0}, roles)", request.getRoles());
//            lqw.apply(StrUtil.format(" find_in_set('{}', roles)", request.getRoles()));
        }
        lqw.eq(SystemAdmin::getBrandId, BrandUtil.getBrandIdByUrl());
        List<SystemAdmin> systemAdmins = dao.selectList(lqw);
        if (CollUtil.isEmpty(systemAdmins)) {
            return CollUtil.newArrayList();
        }
        List<SystemAdminResponse> adminResponseList = new ArrayList<>();
        List<SystemRole> roleList = systemRoleService.getListByMerId(currentAdmin.getMerId());
        for (SystemAdmin admin : systemAdmins) {
            SystemAdminResponse sar = new SystemAdminResponse();
            BeanUtils.copyProperties(admin, sar);
            sar.setLastTime(admin.getUpdateTime());
            List<Integer> roleIds = CrmebUtil.stringToArrayInt(admin.getRoles());
            List<String> roleNames = new ArrayList<>();
            for (Integer roleId : roleIds) {
                if (1 == roleId) {
                    roleNames.add("超级管理员");
                    continue;
                }
                if (2 == roleId) {
                    roleNames.add("商户超管");
                    continue;
                }
                for (SystemRole role : roleList) {
                    if (role.getId().equals(roleId)) {
                        roleNames.add(role.getRoleName());
                    }
                }
            }
            sar.setRoleNames(StringUtils.join(roleNames, ","));
            adminResponseList.add(sar);
        }
        return adminResponseList;
    }

    /**
     * 后台管理员列表
     *
     * @param request          请求参数
     * @param pageParamRequest 分页参数
     * @return List
     */
    @Override
    public List<SystemAdminAgentResponse> getAgentList(SystemAdminRequest request, PageParamRequest pageParamRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //带SystemAdminRequest类的多条件查询
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        if (ObjectUtil.isNotNull(request.getStatus())) {
            lqw.eq(SystemAdmin::getStatus, request.getStatus());
        }
        if (StrUtil.isNotBlank(request.getRealName())) {
            String decode = URLUtil.decode(request.getRealName());
            lqw.and(i -> i.like(SystemAdmin::getRealName, decode)
                    .or().like(SystemAdmin::getAccount, decode));
        }
        SystemAdmin currentAdmin = SecurityUtil.getLoginUserVo().getUser();
        lqw.eq(SystemAdmin::getMerId, currentAdmin.getMerId());
        // 超级管理员查看平台账户 商户超级管理员查看自己和商户管理员
        // 1=1，2,3 2=2，4
//        List<Integer> types = new ArrayList<>();
//        if (currentAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
//            types.add(RoleEnum.MERCHANT_ADMIN.getValue());
//            types.add(RoleEnum.SUPER_MERCHANT.getValue());
//            lqw.in(SystemAdmin::getType, types);
//        } else if (currentAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())) {
//            types.add(RoleEnum.PLATFORM_ADMIN.getValue());
//            types.add(RoleEnum.SUPER_ADMIN.getValue());
//            lqw.in(SystemAdmin::getType, types);
//        } else {
//            Integer roleTypeByCurrentAdmin = systemRoleService.getRoleTypeByCurrentAdmin();
//            types.add(roleTypeByCurrentAdmin);
//            types.add(RoleEnum.BRAND_AGENT.getValue());
//            lqw.in(SystemAdmin::getType, types);
//        }
//        lqw.in(SystemAdmin::getType, 0);
        lqw.in(SystemAdmin::getAgentType, 1);
        if (ObjectUtil.isNotNull(request.getRoles()) && request.getRoles() > 0) {
            lqw.apply(" find_in_set({0}, roles)", request.getRoles());
        }
        lqw.in(SystemAdmin::getCreateId, currentUser.getId());
        lqw.eq(SystemAdmin::getBrandId, BrandUtil.getBrandIdByUrl());
        lqw.orderByDesc(SystemAdmin::getCreateTime);
        List<SystemAdmin> systemAdmins = dao.selectList(lqw);
        if (CollUtil.isEmpty(systemAdmins)) {
            return CollUtil.newArrayList();
        }
        List<SystemAdminAgentResponse> adminResponseList = new ArrayList<>();
        List<SystemRole> roleList = systemRoleService.getListByMerId(currentAdmin.getMerId());
        for (SystemAdmin admin : systemAdmins) {
            SystemAdminAgentResponse sar = new SystemAdminAgentResponse();
            BeanUtils.copyProperties(admin, sar);
//            sar.setLastTime(admin.getUpdateTime());
            List<Integer> roleIds = CrmebUtil.stringToArrayInt(admin.getRoles());
            List<String> roleNames = new ArrayList<>();
            for (Integer roleId : roleIds) {
                if (1 == roleId) {
                    roleNames.add("超级管理员");
                    continue;
                }
                if (2 == roleId) {
                    roleNames.add("商户超管");
                    continue;
                }
                for (SystemRole role : roleList) {
                    if (role.getId().equals(roleId)) {
                        roleNames.add(role.getRoleName());
                    }
                }
            }
            sar.setRoleNames(StringUtils.join(roleNames, ","));
            // 代理的城市列表
            List<SystemAdminAgentCityResponse> cityListByUserId = userAgentService.getCityListByUserId(admin.getId());
            sar.setCityList(cityListByUserId);
            sar.setRoleId(admin.getRoles());
            adminResponseList.add(sar);
        }
        return adminResponseList;
    }

    /**
     * 是否存在角色
     *
     * @param roleId 角色id
     * @return Boolean
     */
    @Override
    public Boolean isExistRole(Integer roleId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId);
        lqw.apply(StrUtil.format(" find_in_set('{}', roles)", roleId));
        lqw.last(" limit 1");
        SystemAdmin systemAdmin = dao.selectOne(lqw);
        return ObjectUtil.isNotNull(systemAdmin);
    }

    /**
     * 新增管理员
     *
     * @param systemAdminAddRequest 新增参数
     * @return Boolean
     */
    @Override
    public Boolean saveAdmin(SystemAdminAddRequest systemAdminAddRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        // 管理员名称唯一校验
        if (checkAccount(systemAdminAddRequest.getAccount())) {
            throw new AppException(AdminResultCode.ADMIN_EXIST);
        }

        SystemAdmin systemAdmin = new SystemAdmin();
        BeanUtils.copyProperties(systemAdminAddRequest, systemAdmin);

        String pwd = CrmebUtil.encryptPassword(systemAdmin.getPwd(), systemAdmin.getAccount());
        systemAdmin.setPwd(pwd);
        systemAdmin.setMerId(currentUser.getMerId());
        systemAdmin.setType(systemRoleService.getRoleTypeByCurrentAdmin());
        systemAdmin.setBrandId(BrandUtil.getBrandIdByUrl());
        return save(systemAdmin);
    }

    /**
     * 新增代理登陆人
     *
     * @param request 新增参数
     * @return Boolean
     */
    @Override
    public Boolean saveAdminAgent(SystemAdminAgentAddRequest request) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        // 代理用户
        User user = userService.getOne(new LambdaQueryWrapper<User>().select(User::getId,
                User::getAccount).eq(User::getId, request.getUid()));
        if (ObjectUtil.isNull(user)) {
            throw new AppException("用户不存在");
        }
        // 管理员名称唯一校验
        if (checkAccount(request.getAccount())) {
            throw new AppException(AdminResultCode.ADMIN_EXIST);
        }
        // 检查权限
        List<String> cityNameList = getCityList(request.getCityList());
        doCheck(cityNameList, currentUser.getId());

        request.getSystemRole().setRoleName("代理"+request.getAccount());
        if(request.getSystemRole()!=null && !StringUtil.isEmpty(request.getSystemRole().getRules())){
            String rules = request.getSystemRole().getRules();
            //默认添加角色权限
            rules=rules+",1253,1272,1254,1256,1257,1258,1259,1260";
            request.getSystemRole().setRules(rules);
            SystemRole systemRole = systemRoleService.addRole(request.getSystemRole());
            if (systemRole==null || systemRole.getId() == null){
                throw new AppException("添加角色失败");
            }
            request.setRoles(systemRole.getId().toString());
        }

        SystemAdmin systemAdmin = new SystemAdmin();
        BeanUtils.copyProperties(request, systemAdmin);
        if (StrUtil.isBlank(systemAdmin.getPhone())) {
            systemAdmin.setPhone(user.getPhone());
        }

        String pwd = CrmebUtil.encryptPassword(systemAdmin.getPwd(), systemAdmin.getAccount());
        systemAdmin.setPwd(pwd);
        systemAdmin.setMerId(currentUser.getMerId());
        systemAdmin.setType(systemRoleService.getRoleTypeByCurrentAdmin());
        systemAdmin.setAgentUid(user.getId());
        systemAdmin.setAgentType(1);
        systemAdmin.setCreateId(currentUser.getId());
        systemAdmin.setBrandId(BrandUtil.getBrandIdByUrl());
        boolean save = save(systemAdmin);
        if (!save) {
            throw new AppException("添加失败");
        }
        // 代理用户
        List<UserAgent> list = new ArrayList<>();
        for (SystemAdminAgentAddCityRequest city : request.getCityList()) {
            UserAgent userAgent = new UserAgent();
            BeanUtils.copyProperties(city, userAgent);
            userAgent.setId(null);
            userAgent.setBrandId(BrandUtil.getBrandIdByUrl());
            userAgent.setAgentLevel(city.getAgentLevel());
            userAgent.setSystemAdminId(systemAdmin.getId());
            userAgent.setUserId(user.getId());
            list.add(userAgent);
        }
        userAgentService.saveBatch(list);
        return true;
    }

    /**
     * 检查权限
     * @param request
     * @param curAdminId
     */
    private void checkAdd(SystemAdminAgentAddRequest request, Integer curAdminId) {
        List<String> cityNameList = getCityList(request.getCityList());
        doCheck(cityNameList, curAdminId);
    }

    private void doCheck(List<String> cityNameList, Integer curAdminId) {

        List<SystemAdminAgentCityResponse> nameList = userAgentService.getCityListByUserId(curAdminId);
        if (CollUtil.isNotEmpty(nameList)) {
            List<String> oldCityNameList = nameList.stream().map(SystemAdminAgentCityResponse::getCity).distinct().collect(Collectors.toList());
            int i = 0;
            for (SystemAdminAgentCityResponse response : nameList) {
                for (String name : cityNameList) {
                    if (name.equals(response.getCity())) {
                        throw new AppException("不能添加该地区");
                    }
                    if (name.startsWith(response.getCity())) {
                        i++;
                    }
                }
            }
            if (i != cityNameList.size()) {
                throw new AppException("必须选择代理人所属区域下方的地区");
            }
            int matchCount = 0;
            for (String name : cityNameList) {
                if (inList(name, oldCityNameList)) {
                    matchCount++;
                }
            }
            if (matchCount != cityNameList.size()) {
                throw new AppException("不能添加其他地区");
            }

        }
    }

    private boolean inList(String name, List<String> oldCityNameList) {
        for (String s : oldCityNameList) {
            if(name.contains(s)){
                return true;
            }
        }
        return false;
    }

    private List<String> getCityList(List<SystemAdminAgentAddCityRequest> regionList) {
        List<String> list = new ArrayList<>();
        for (SystemAdminAgentAddCityRequest brandAgentItemSaveRequest : regionList) {
            List<String> regionNameList = new ArrayList<>();
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getProvince())) {
                regionNameList.add(brandAgentItemSaveRequest.getProvince());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getCity())) {
                regionNameList.add(brandAgentItemSaveRequest.getCity());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getDistrict())) {
                regionNameList.add(brandAgentItemSaveRequest.getDistrict());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getStreet())) {
                regionNameList.add(brandAgentItemSaveRequest.getStreet());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getTribe())) {
                regionNameList.add(brandAgentItemSaveRequest.getTribe());
            }
            if (StrUtil.isNotBlank(brandAgentItemSaveRequest.getCommunity())) {
                regionNameList.add(brandAgentItemSaveRequest.getCommunity());
            }
            String join = CollUtil.join(regionNameList, "/");
            list.add(join);
        }
        return list;
    }

    /**
     * 管理员名称唯一校验
     *
     * @param account 管理员账号
     * @return Boolean
     */
    @Override
    public Boolean checkAccount(String account) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getAccount, account);
        lqw.eq(SystemAdmin::getIsDel, false);
        lqw.eq(SystemAdmin::getBrandId, BrandUtil.getBrandIdByUrl());
        return dao.selectCount(lqw) > 0;
    }

    /**
     * 更新管理员
     */
    @Override
    public Boolean updateAdmin(SystemAdminUpdateRequest systemAdminRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        SystemAdmin adminDetail = getDetail(systemAdminRequest.getId());
        // 超级管理员不允许编辑
        if (adminDetail.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || adminDetail.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(adminDetail.getMerId())) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        verifyAccount(systemAdminRequest.getId(), systemAdminRequest.getAccount());
        SystemAdmin systemAdmin = new SystemAdmin();
        systemAdmin.setId(systemAdminRequest.getId());
        systemAdmin.setAccount(systemAdminRequest.getAccount());
        systemAdmin.setRealName(systemAdminRequest.getRealName());
        systemAdmin.setRoles(systemAdminRequest.getRoles());
        systemAdmin.setStatus(systemAdminRequest.getStatus());
        if (StrUtil.isNotBlank(systemAdminRequest.getPhone())) {
            systemAdmin.setPhone(systemAdminRequest.getPhone());
        }
        systemAdmin.setMerId(currentUser.getMerId());
        return updateById(systemAdmin);
    }

    /**
     * 更新管理员
     */
    @Override
    public Boolean updateAgentAdmin(SystemAdminAgentUpdateRequest systemAdminRequest) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        SystemAdmin systemAdmin = getById(systemAdminRequest.getId());
        if (ObjectUtil.isNull(systemAdmin) || systemAdmin.getIsDel()) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (systemAdmin.getAgentType().equals(0)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "非代理账号，不允许删除");
        }
        if (!systemAdmin.getBrandId().equals(BrandUtil.getBrandIdByUrl())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "非当前品牌商账号，不允许删除");
        }
        // 检查权限
        List<String> cityNameList = getCityList(systemAdminRequest.getCityList());
        doCheck(cityNameList, currentUser.getId());

        verifyAccount(systemAdminRequest.getId(), systemAdminRequest.getAccount());

        //更新角色权限
        if (systemAdminRequest.getSystemRole()!=null&& !StringUtil.isEmpty(systemAdminRequest.getSystemRole().getRules())){
            systemRoleService.edit(systemAdminRequest.getSystemRole());
        }

        SystemAdmin systemAdminUpdate = new SystemAdmin();
        systemAdminUpdate.setId(systemAdminRequest.getId());
        systemAdminUpdate.setAccount(systemAdminRequest.getAccount());
        systemAdminUpdate.setRealName(systemAdminRequest.getRealName());
        systemAdminUpdate.setRoles(systemAdminRequest.getRoles());
        systemAdminUpdate.setStatus(systemAdminRequest.getStatus());
        if (StrUtil.isNotBlank(systemAdminRequest.getPhone())) {
            systemAdminUpdate.setPhone(systemAdminRequest.getPhone());
        }
        systemAdminUpdate.setMerId(currentUser.getMerId());
        boolean b = updateById(systemAdminUpdate);
        if (!b) {
            throw new AppException("更新失败");
        }
        // 代理用户
        List<UserAgent> list = new ArrayList<>();

        // 检查分类
        List<UserAgent> crowdProjectItemsList = userAgentService.getListByAdminId(systemAdminUpdate.getId());
        if (CollUtil.isNotEmpty(crowdProjectItemsList)) {
            List<Integer> oldIds = crowdProjectItemsList.stream().map(UserAgent::getId).distinct().collect(Collectors.toList());
            List<Integer> newIds = systemAdminRequest.getCityList().stream().map(SystemAdminAgentAddCityRequest::getId).distinct().collect(Collectors.toList());
            // 已删除的id 计算差集，找出在 list1 中但不在 list2 中的元素
            Collection<Integer> delIds = CollUtil.disjunction(oldIds, newIds);
            if (CollUtil.isNotEmpty(delIds)) {
                userAgentService.removeByIds(delIds);
            }
        }

        for (SystemAdminAgentAddCityRequest city : systemAdminRequest.getCityList()) {
            if (ObjectUtil.isNotNull(city.getId())) {
                continue;
            }
            UserAgent userAgent = new UserAgent();
            BeanUtils.copyProperties(city, userAgent);
            userAgent.setId(null);
            userAgent.setBrandId(BrandUtil.getBrandIdByUrl());
            userAgent.setAgentLevel(city.getAgentLevel());
            userAgent.setSystemAdminId(systemAdmin.getId());
            userAgent.setUserId(systemAdmin.getAgentUid());
            list.add(userAgent);
        }
        if (CollUtil.isNotEmpty(list)) {
            userAgentService.saveBatch(list);
        }
        return true;
    }

    /**
     * 删除管理员
     *
     * @param id 管理员id
     * @return 删除结果
     */
    @Override
    public Boolean removeAdmin(Integer id) {
        SystemAdmin perDelAdmin = getDetail(id);
        if (perDelAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || perDelAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许删除");
        }
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        if (!admin.getMerId().equals(perDelAdmin.getMerId())) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        return removeById(id);
    }

    /**
     * 修改后台管理员状态
     *
     * @param id     管理员id
     * @param status 状态
     * @return Boolean
     */
    @Override
    public Boolean updateStatus(Integer id, Boolean status) {
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();
        // 超级管理员不允许编辑
        SystemAdmin systemAdmin = getDetail(id);
        if (systemAdmin.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || systemAdmin.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(systemAdmin.getMerId())) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (systemAdmin.getStatus().equals(status)) {
            return true;
        }
        systemAdmin.setStatus(status);
        return updateById(systemAdmin);
    }

    @Override
    public Boolean updateAgentStatus(Integer id, Boolean status) {
        SystemAdmin systemAdmin = getById(id);
        if (ObjectUtil.isNull(systemAdmin) || systemAdmin.getIsDel()) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (systemAdmin.getAgentType().equals(0)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "非代理账号，不允许删除");
        }
        if (!systemAdmin.getBrandId().equals(BrandUtil.getBrandIdByUrl())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "非当前品牌商账号，不允许删除");
        }

        if (systemAdmin.getStatus().equals(status)) {
            return true;
        }
        systemAdmin.setStatus(status);
        return updateById(systemAdmin);
    }

    /**
     * 管理员详情
     *
     * @param id 管理员id
     * @return SystemAdmin
     */
    @Override
    public SystemAdmin getDetail(Integer id) {
        SystemAdmin systemAdmin = getById(id);
        if (ObjectUtil.isNull(systemAdmin) || systemAdmin.getIsDel()) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        if (admin.getMerId() > 0) {
            if (!admin.getMerId().equals(systemAdmin.getMerId())) {
                throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
            }
        }
        return systemAdmin;
    }

    /**
     * 获取管理员名称map
     *
     * @param idList id列表
     * @return Map
     */
    @Override
    public Map<Integer, String> getNameMapByIdList(List<Integer> idList) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId, SystemAdmin::getRealName);
        lqw.in(SystemAdmin::getId, idList);
        List<SystemAdmin> adminList = dao.selectList(lqw);
        Map<Integer, String> map = CollUtil.newHashMap();
        adminList.forEach(admin -> {
            map.put(admin.getId(), admin.getRealName());
        });
        return map;
    }

    /**
     * 修改后台管理员手机号
     */
    @Override
    public Boolean updatePassword(SystemAdminUpdatePwdRequest request) {
        if (!request.getPassword().equals(request.getConfirmPassword())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "两次密码输入不一致");
        }
        SystemAdmin currentUser = SecurityUtil.getLoginUserVo().getUser();

        SystemAdmin adminDetail = getDetail(request.getId());
        // 超级管理员不允许编辑
        if (adminDetail.getType().equals(RoleEnum.SUPER_ADMIN.getValue())
                || adminDetail.getType().equals(RoleEnum.SUPER_MERCHANT.getValue())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "系统内置权限，不允许编辑");
        }
        if (!currentUser.getMerId().equals(adminDetail.getMerId())) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        SystemAdmin newAdmin = new SystemAdmin();
        newAdmin.setId(request.getId());
        newAdmin.setPwd(CrmebUtil.encryptPassword(request.getPassword(), adminDetail.getAccount()));
        return updateById(newAdmin);
    }

    /**
     * 商户后台管理员短信开关
     *
     * @param adminId 商户管理员ID
     */
    @Override
    public Boolean updateReceiveSms(Integer adminId) {
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        if (admin.getMerId().equals(0)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "平台管理员无接口短信开关");
        }
        SystemAdmin systemAdmin = getById(adminId);
        if (!admin.getMerId().equals(systemAdmin.getMerId())) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (!systemAdmin.getIsSms() && StrUtil.isBlank(systemAdmin.getPhone())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "请先为管理员设置手机号");
        }
        systemAdmin.setIsSms(!systemAdmin.getIsSms());
        return updateById(systemAdmin);
    }

    /**
     * 获取接收短信管理员列表
     *
     * @param merId 商户ID
     */


    public List<SystemAdmin> findReceiveSmsAdminListByMerId(Integer merId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId, SystemAdmin::getPhone, SystemAdmin::getRealName);
        lqw.eq(SystemAdmin::getMerId, merId);
        lqw.eq(SystemAdmin::getIsSms, 1);
        lqw.eq(SystemAdmin::getStatus, 1);
        lqw.eq(SystemAdmin::getIsDel, 0);
        return dao.selectList(lqw);
    }

    /**
     * 校验账号唯一性（管理员更新时）
     *
     * @param id      管理员id
     * @param account 管理员账号
     */
    @Override
    public void verifyAccount(Integer id, String account) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.ne(SystemAdmin::getId, id);
        lqw.eq(SystemAdmin::getAccount, account);
        SystemAdmin systemAdmin = dao.selectOne(lqw);
        if (ObjectUtil.isNotNull(systemAdmin)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "账号已存在");
        }
    }

    @Override
    public Integer getIdByBrandId(Integer brandId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId);
        lqw.eq(SystemAdmin::getBrandId, brandId);
        lqw.eq(SystemAdmin::getIsDel, false);
        SystemAdmin systemAdmin = dao.selectOne(lqw);
        if (ObjectUtil.isNull(systemAdmin)) {
            return null;
        }
        return systemAdmin.getId();
    }

    @Override
    public boolean checkAccountPlarform(String account, Integer brandId) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.eq(SystemAdmin::getAccount, account);
        lqw.eq(SystemAdmin::getIsDel, false);
        lqw.eq(SystemAdmin::getBrandId, brandId);
        return dao.selectCount(lqw) > 0;
    }

    @Override
    public Integer getBrandIdById(Integer id) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getBrandId);
        lqw.eq(SystemAdmin::getId, id);
        lqw.eq(SystemAdmin::getIsDel, false);
        SystemAdmin systemAdmin = dao.selectOne(lqw);
        if (systemAdmin == null) {
            return 0;
        }
        return systemAdmin.getBrandId();
    }

    @Override
    public SystemAdminAgentDetailResponse getAgentDetail(Integer id) {
        SystemAdmin systemAdmin = getById(id);
        if (ObjectUtil.isNull(systemAdmin) || systemAdmin.getIsDel()) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        SystemAdmin admin = SecurityUtil.getLoginUserVo().getUser();
        if (admin.getMerId() > 0) {
            if (!admin.getMerId().equals(systemAdmin.getMerId())) {
                throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
            }
        }
        SystemAdminAgentDetailResponse response = new SystemAdminAgentDetailResponse();
        BeanUtil.copyProperties(systemAdmin, response);
        // 角色信息
        List<SystemRole> roleList = systemRoleService.getListByMerId(systemAdmin.getBrandId(), 0);
        List<Integer> roleIds = CrmebUtil.stringToArrayInt(systemAdmin.getRoles());
        List<String> roleNames = new ArrayList<>();
        for (Integer roleId : roleIds) {
            for (SystemRole role : roleList) {
                if (role.getId().equals(roleId)) {
                    roleNames.add(role.getRoleName());
                }
            }
        }
        response.setRoleNames(StringUtils.join(roleNames, ","));

        // 代理用户城市信息
        List<UserAgent> cityList = userAgentService.getListByAdminId(systemAdmin.getId());
        List<SystemAdminAgentDetailCityResponse> responseList = new ArrayList<>();
        if (CollUtil.isNotEmpty(cityList)) {
            for (UserAgent userAgent : cityList) {
                SystemAdminAgentDetailCityResponse res = new SystemAdminAgentDetailCityResponse();
                BeanUtil.copyProperties(userAgent, res);
                responseList.add(res);
            }
        }
        response.setCityList(responseList);
        return response;
    }

    @Override
    public SystemAdmin getAgentInfo(Integer id) {
        LambdaQueryWrapper<SystemAdmin> lqw = Wrappers.lambdaQuery();
        lqw.select(SystemAdmin::getId, SystemAdmin::getType, SystemAdmin::getRealName);
        lqw.eq(SystemAdmin::getId, id);
        lqw.eq(SystemAdmin::getIsDel, 0);
        return getOne(lqw);
    }

    @Override
    public boolean removeAgentAdmin(Integer id) {
        SystemAdmin systemAdmin = getById(id);
        if (ObjectUtil.isNull(systemAdmin) || systemAdmin.getIsDel()) {
            throw new AppException(AdminResultCode.ADMIN_NOT_EXIST);
        }
        if (systemAdmin.getAgentType().equals(0)) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "非代理账号，不允许删除");
        }
        if (!systemAdmin.getBrandId().equals(BrandUtil.getBrandIdByUrl())) {
            throw new AppException(CommonResultCode.VALIDATE_FAILED, "非当前品牌商账号，不允许删除");
        }
        return removeById(id);
    }

    @Override
    public AgentCurLoginInfoResponse getCurLoginInfo() {
        SystemAdmin currentAdmin = SecurityUtil.getLoginUserVo().getUser();
        AgentCurLoginInfoResponse agentCurLoginInfoResponse = new AgentCurLoginInfoResponse();
        agentCurLoginInfoResponse.setAgentType(currentAdmin.getAgentType());
        return agentCurLoginInfoResponse;
    }

    /**
     * 登录之前查询权限带上超管标识
     *
     * @param type 用户类型
     */
    private List<Integer> addSuperRoleType(Integer type) {
        List<Integer> types = new ArrayList<>();
        if (type.equals(RoleEnum.PLATFORM_ADMIN.getValue())) {
            types.add(RoleEnum.SUPER_ADMIN.getValue());
            types.add(RoleEnum.PLATFORM_ADMIN.getValue());
        }
        if (type.equals(RoleEnum.MERCHANT_ADMIN.getValue())) {
            types.add(RoleEnum.SUPER_MERCHANT.getValue());
            types.add(RoleEnum.MERCHANT_ADMIN.getValue());
        }
        if (type.equals(RoleEnum.REGION_ADMIN.getValue())) {
            types.add(RoleEnum.REGION_SUPER_ADMIN.getValue());
            types.add(RoleEnum.REGION_ADMIN.getValue());
        }
        if (type.equals(RoleEnum.BRAND_ADMIN.getValue())){
            types.add(RoleEnum.BRAND_SUPER_ADMIN.getValue());
            types.add(RoleEnum.BRAND_ADMIN.getValue());
        }
        return types;
    }

}

